import java.lang.ref.ReferenceQueue;
import java.lang.ref.SoftReference;

/**
 * Java软引用:优先级次于强引用
 * <p>
 * 特点:当内存不足时会被回收
 *
 * @author <a href="mailto:wengyj@59store.com">翁英健</a>
 * @version 1.1 16/4/3
 * @since 1.1
 */
public class SoftReferenceDemo {


    /**
     * 回收之前:引用元素:=java.lang.Object@1d44bcfa
     * 回收之前:队列元素:=null
     * 回收之前:引用元素:=java.lang.Object@1d44bcfa
     * 回收之前:队列元素:=null
     *
     * @param args
     * @throws InterruptedException
     */
    public static void main(String[] args) throws InterruptedException {

        Object o = new Object();
        System.out.println(o);
        //引用队列
        ReferenceQueue<Object> referenceQueue = new ReferenceQueue<>();
        SoftReference<Object> softReference = new SoftReference<>(o, referenceQueue);

        System.out.println("回收之前:引用元素:=" + softReference.get());
        System.out.println("回收之前:队列元素:=" + referenceQueue.poll());

        o = null;
        System.gc();
        Thread.sleep(1000);

        System.out.println("回收之前:引用元素:=" + softReference.get());
        System.out.println("回收之前:队列元素:=" + referenceQueue.poll());
    }
}
